﻿#include "worker.h"

Worker::Worker(QString *ip)
    : destIP(ip)
{
    isRun = false;

    videoOutput = new VideoOutput();
    rtpSender = new RtpPacketSender(destIP);
    videoCapturer = new VideoCapturer();
    audioCapturer = new AudioCapturer();

    videoCapturer->videoOutput = videoOutput;
    spsFrame = nullptr;
    ppsFrame = nullptr;
    spsLen = 0;
    ppsLen = 0;
}

Worker::~Worker()
{
    delete videoOutput;
    videoOutput = nullptr;
    delete rtpSender;
    rtpSender = nullptr;
    delete videoCapturer;
    videoCapturer = nullptr;
    delete audioCapturer;
    audioCapturer = nullptr;
}

void Worker::msSleep(int ms)
{
    //实现毫秒级别的[非阻塞]睡眠

    QEventLoop loop; //Qt中的一个事件循环类，它用于处理事件和等待事件的发生
    QTimer::singleShot(ms, &loop, &QEventLoop::quit); //ms毫秒之后退出事件循环
    loop.exec(); //启动事件循环
}


void Worker::setRunState(bool start)
{
    isRun = start;

    if(start)
        this->start();
}

void Worker::parseSPS_PPS(AVCodecContext *videoCtx)
{
    //参考 https://blog.csdn.net/heng615975867/article/details/120026185

    if(!videoCtx)
        return;

    //sps pps保存在解码器上下文的extradata字段 一般都是各1个 这里按照一个解析
    char *extraData = (char *)videoCtx->extradata;
    int curLen = 6;

    spsLen = hexArrayToDec(extraData + curLen, 2);
    curLen += 2;
    spsFrame = new char[spsLen];
    memcpy(spsFrame, extraData + curLen, spsLen);

    curLen += spsLen + 1;
    ppsLen = hexArrayToDec(extraData + curLen, 2);
    curLen += 2;
    ppsFrame = new char[ppsLen];
    memcpy(ppsFrame, extraData + curLen, ppsLen);
}

void Worker::sendPacketToRtpSender(AVPacket *packet, AVPacketType type)
{
    if(packet == nullptr)
        return;

    int size = packet->size;
    char *data = (char *)av_malloc(size);
    memcpy(data, packet->data, size);
    AVPacket *newPacket = av_packet_alloc();
    av_packet_from_data(newPacket, (uint8_t *)data, size);

    ReadyPacket *readyPacket = new ReadyPacket();
    readyPacket->packet = newPacket;
    readyPacket->type = type;

    rtpSender->writePacket(readyPacket);
}

void Worker::doTaskRealStart()
{
    //设置视频音频的RTP发送者
    videoCapturer->rtpSender = rtpSender;
    audioCapturer->rtpSender = rtpSender;

    //启动视频抓取、音频抓取线程
    videoCapturer->setRunState(true);
    audioCapturer->setRunState(true);

    //启动RTP发送者
    rtpSender->setRunState(true);
}

void Worker::doTaskRealStop()
{
    //停止三个线程
    videoCapturer->setRunState(false);
    audioCapturer->setRunState(false);
    rtpSender->setRunState(false);
}

void Worker::run()
{
    while(true)
    {
        QThread::sleep(5);
    }
}
